﻿using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace bonus.Controllers
{
	/// <summary>
	/// 订单控制器
	/// </summary>
	public class OrderController : Controller
	{
		/// <summary>
		/// 报单列表
		/// </summary>
		/// <returns></returns>
		public ActionResult Index()
		{

			return View();
		}


		/// <summary>
		/// 全部显示(开通账号)
		/// </summary>
		/// <returns></returns>
		public ActionResult OrderAll()
		{
			return View();
		}

		/// <summary>
		/// 添加保单
		/// </summary>
		/// <returns></returns>
		public ActionResult addOrder()
		{
			Repository.Repository tool = new Repository.Repository();

			var list = tool.GetAll<Models.Products>();

			if (list == null)
			{
				list = new List<Models.Products>();
			}

			ViewBag.ProductList = list;

			return View();
		}

		//订单分页数据
		[HttpPost]
		public JsonResult PartialOrder(string key, DateTime? startDT, DateTime? endDT, int index = 1, int size = 10, int state = -1)
		{
			Repository.Repository tool = new Repository.Repository();

			if (startDT == null)
			{
				startDT = DateTime.Now.AddYears(-2);
			}

			if (endDT == null)
			{
				endDT = DateTime.Now;
			}

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户权限不够或未登陆" });
			}

			if (user.UserType == Models.User.TypeClass.ADMIN)
			{
				if (string.IsNullOrEmpty(key))
				{
					var filter = Builders<Models.Order>.Filter.Where(p => p.AddDT >= startDT && p.AddDT < endDT);


					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}

					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyy-MM-dd"),
							AddPC = item.AddPC,
							Wather = item.Wather,
							SaleName = item.SaleName,
							State = item.State,//Models.Order.StateClass.GetState(item.State),
							States = Models.Order.StateClass.GetState(item.State),
							SaleNo = item.SaleNo,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Type = item.Type,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
				else
				{

					var filter = Builders<Models.Order>.Filter.Where(p => p.UserName.Contains(key) || p.OrderNo.Contains(key) || p.UserNo.Contains(key) || p.UserNo.Contains(key) || p.AddPC.Contains(key) || p.Type.Contains(key) && p.AddDT >= startDT && p.AddDT < endDT);
					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => p.UserName.Contains(key) || p.OrderNo.Contains(key) || p.UserNo.Contains(key) || p.UserNo.Contains(key) || p.AddPC.Contains(key) || p.Type.Contains(key) && p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}
					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyyMMdd HH:mm"),
							AddPC = item.AddPC,
							SaleName = item.SaleName,
							State = item.State,
							States = Models.Order.StateClass.GetState(item.State),
							Wather = item.Wather,
							SaleNo = item.SaleNo,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Type = item.Type,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
			}
			else if (user.UserType == Models.User.TypeClass.User)
			{
				if (string.IsNullOrEmpty(key))
				{

					var filter = Builders<Models.Order>.Filter.Where(p => p.UserNo == user.NO && p.AddDT >= startDT && p.AddDT < endDT);
					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => p.UserNo == user.NO && p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}
					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyy-MM-dd"),
							AddPC = item.AddPC,
							Wather = item.Wather,
							SaleName = item.SaleName,
							State = item.State,//Models.Order.StateClass.GetState(item.State),
							States = Models.Order.StateClass.GetState(item.State),
							SaleNo = item.SaleNo,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Type = item.Type,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
				else
				{

					var filter = Builders<Models.Order>.Filter.Where(p => (p.UserName.Contains(key) || p.AddPC.Contains(key) || p.Type.Contains(key)) && p.UserNo == user.NO && p.AddDT >= startDT && p.AddDT < endDT);
					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => (p.UserName.Contains(key) || p.AddPC.Contains(key) || p.Type.Contains(key)) && p.UserNo == user.NO && p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}
					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyyMMdd HH:mm"),
							AddPC = item.AddPC,
							SaleName = item.SaleName,
							State = item.State,
							States = Models.Order.StateClass.GetState(item.State),
							Wather = item.Wather,
							SaleNo = item.SaleNo,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Type = item.Type,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
			}
			else
			{
				if (string.IsNullOrEmpty(key))
				{

					var filter = Builders<Models.Order>.Filter.Where(p => p.AddPC == user.NO && p.AddDT >= startDT && p.AddDT < endDT);
					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => p.AddPC == user.NO && p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}
					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyy-MM-dd"),
							AddPC = item.AddPC,
							Wather = item.Wather,
							SaleName = item.SaleName,
							State = item.State,//Models.Order.StateClass.GetState(item.State),
							States = Models.Order.StateClass.GetState(item.State),
							SaleNo = item.SaleNo,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Type = item.Type,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
				else
				{
					var filter = Builders<Models.Order>.Filter.Where(p => (p.UserName.Contains(key) || p.UserNo.Contains(key) || p.Type.Contains(key)) && p.AddPC == user.NO && p.AddDT >= startDT && p.AddDT < endDT);
					if (state >= 0)
					{
						filter = Builders<Models.Order>.Filter.Where(p => (p.UserName.Contains(key) || p.UserNo.Contains(key) || p.Type.Contains(key)) && p.AddPC == user.NO && p.AddDT >= startDT && p.AddDT < endDT && p.State == state);
					}
					var count = tool.Count<Models.Order>(filter);

					var page = Math.Ceiling(Convert.ToDouble(count) / size);//总页数

					var list = tool.GetMany<Models.Order>(filter, "AddDT:-1", size, index);

					ICollection<object> Entities = new List<object>() { };
					foreach (var item in list)
					{

						object i = new
						{
							Id = item._id.ToString(),
							OrderNo = item.OrderNo,
							AddDT = item.AddDT.ToString("yyyyMMdd HH:mm"),
							AddPC = item.AddPC,
							SaleName = item.SaleName,
							State = item.State,
							States = Models.Order.StateClass.GetState(item.State),
							Wather = item.Wather,
							SaleNo = item.SaleNo,
							UserNo = string.IsNullOrEmpty(item.UserNo) ? "无" : item.UserNo,
							Type = item.Type,
							BuyType = Models.User.TypeClass.GetType(item.BuyType),
							Money = item.Money.ToString("0.##"),
							UserName = item.UserName,
							Mobile = item.Mobile,
							PV = item.PV,
						};
						Entities.Add(i);

					}
					return Json(new { Code = "OK", Data = Entities, total = count });//Totle:总条数  Count:总页数   Index 当前页
				}
			}



		}

		/// <summary>
		/// 确认提现页面
		/// </summary>
		/// <returns></returns>
		public ActionResult ConWithdraw()
		{
			Repository.Repository tool = new Repository.Repository();

			var filter = Builders<Models.Journal>.Filter.Eq("State", 0);

			var list = tool.GetMany(filter);

			return View(list);
		}

		/// <summary>
		/// 提现历史列表
		/// </summary>
		/// <returns></returns>
		public ActionResult ConWithdrawView()
		{
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户权限不够或未登陆" });
			}

			var filter = Builders<Models.Journal>.Filter.Where(p => p.Type == Models.Journal.TypeClass.WITHDRAW && p.State == 1);

			var list = tool.GetMany<Models.Journal>(filter, "AddDT:-1");
			return View(list);
		}

		/// <summary>
		/// 提交订单
		/// </summary>
		/// <param name="order"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult Index(Models.Order order)
		{
			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (user == null)
			{
				return Json(new { Code = "FAIL", Msg = "请登录后在进行报单" });
			}

			if (user.UserType == Models.User.TypeClass.User)
			{
				return Json(new { Code = "FAIL", Msg = "账户无此功能" });
			}

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == order.SaleNo);
			var saleUser = tool.GetOne(filter);

			if (saleUser == null)
			{
				return Json(new { Code = "FAIL", Msg = "售货人不存在" });
			}

			if (saleUser.Bind == null || (saleUser.Bind != null && !saleUser.Bind.Contains(user.NO)))
			{
				if (string.IsNullOrEmpty(saleUser.Cantent))
				{
					if (user.UserType != Models.User.TypeClass.ADMIN)
					{
						return Json(new { Code = "FAIL", Msg = "请联系管理员进行报单" });
					}
				}
				else
				{
					var filterC = Builders<Models.User>.Filter.Where(p => p.NO == saleUser.Cantent);
					var cantent = tool.GetOne(filterC);

					if (cantent == null)
					{
						if (saleUser.Cantent != user.NO && user.UserType != Models.User.TypeClass.ADMIN)
						{
							return Json(new { Code = "FAIL", Msg = "该用户不在该账户的管辖范围" });
						}
					}
					else
					{
						if (saleUser.Cantent != user.NO && cantent.Cantent != user.NO && user.UserType != Models.User.TypeClass.ADMIN)
						{
							return Json(new { Code = "FAIL", Msg = "该用户不在该账户的管辖范围" });
						}
					}

				}
			}

			int pvs = 0;

			foreach (var item in order.Products)
			{
				var filterP = Builders<Models.Products>.Filter.Where(p => p.ProNo == item.No && !p.UnSale);
				var product = tool.GetOne(filterP);
				if (product == null)
				{
					return Json(new { Code = "FAIL", Msg = "产品不存在或已下架" });
				}

				if (item.Money != product.Money)
				{
					return Json(new { Code = "FAIL", Msg = "产品价格和后台不匹配" });
				}

				pvs += product.PV * item.Num;

			}

			order._id = ObjectId.GenerateNewId();

			string str = saleUser.Cantent;

			if (saleUser.Bind != null && saleUser.Bind.Contains(user.NO))
			{
				str = user.NO;
			}

			order.SaleNo = order.SaleNo;
			order.AddDT = DateTime.Now;
			order.AddPC = str;
			order.BuyType = user.UserType;
			order.Type = "学员零售";
			order.State = 0;
			order.OrderNo = DateTime.Now.ToString("yyyyMMddHHmmssffff");
			order.SaleName = saleUser.Name;
			decimal money = 0;
			for (int i = 0; i < order.Products.Count; i++)
			{
				order.Products[i].Sort = 1100 + i + 1;
				money += order.Products[i].Num * order.Products[i].Money;
			}
			order.Money = money;
			order.PV = pvs;
			var result = tool.AddOneAsync(order);

			return Json(new { Code = "OK", Msg = "添加成功" });
		}

		/// <summary>
		/// 给公司和服务商返钱
		/// </summary>
		/// <param name="order">订单</param>
		/// <param name="contents">服务商</param>
		/// <param name="rate">费率</param>
		public string SetContent(Models.Order order)
		{
			Repository.Repository tool = new Repository.Repository();
			string str = "";
			var fcantent = Builders<Models.User>.Filter.Eq("NO", order.AddPC);

			var content = tool.GetOne(fcantent);

			var firterandmin = Builders<Models.User>.Filter.Where(p => p.UserType == Models.User.TypeClass.ADMIN);

			var adminu = tool.GetOne(firterandmin);

			if (content != null && content.UserType == Models.User.TypeClass.COMPANY)
			{
				Models.Journal jcontent = new Models.Journal();

				jcontent.AddDT = DateTime.Now;
				jcontent.In = order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU;
				jcontent.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				jcontent.Operator = "Sys";
				jcontent.GetNO = content.NO;
				jcontent.Name = content.Name;
				jcontent.Out = 0;
				jcontent.Remarks = "得到管理费:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI).ToString("0.##") + ";物流津贴:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU).ToString("0.##");
				jcontent.OrderMoney = order.PV;
				jcontent.OrderNo = order.OrderNo;
				jcontent.State = 1;
				jcontent.Rest = order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU + content.Money;
				jcontent.Type = Models.Journal.TypeClass.GUANLI;
				jcontent.Title = Models.Journal.TypeClass.GetType(jcontent.Type) + ";订单:" + order.OrderNo;
				jcontent._id = ObjectId.GenerateNewId();

				var contentresult = tool.AddOneAsync(jcontent);


				Models.Journal admin = new Models.Journal();

				admin.AddDT = DateTime.Now;
				admin.In = 0;
				admin.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				admin.Operator = "Sys";
				admin.GetNO = "Sys";
				admin.Name = "Sys";
				admin.OrderMoney = order.PV;
				admin.OrderNo = order.OrderNo;
				admin.Out = order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU;
				admin.Remarks = "补贴 管理费:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI).ToString("0.##") + ";物流津贴:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU).ToString("0.##");
				admin.State = 1;
				admin.Rest = 0;
				admin.Type = Models.Journal.TypeClass.BUTIE;
				admin.Title = Models.Journal.TypeClass.GetType(admin.Type) + ";订单:" + order.OrderNo;
				admin._id = ObjectId.GenerateNewId();
				var adminresult = tool.AddOneAsync(admin);


				var cupdate = Builders<Models.User>.Update.Set("Money", order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU + content.Money);

				var caddresult = tool.UpdateOne(content._id.ToString(), cupdate);
				str += "公司:" + content.Name + " 编号:" + content.NO + "得到:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU).ToString("0.##") + ";";

				if (adminu != null)
				{
					var cupdatead = Builders<Models.User>.Update.Set("Money", adminu.Money - (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI + order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU));

					var adminupdate = tool.UpdateOne(adminu._id.ToString(), cupdatead);
				}



			}
			else if (content != null && content.UserType == Models.User.TypeClass.CONTENT)
			{
				var adminmoney = adminu.Money;

				Models.Journal jcontent = new Models.Journal();

				jcontent.AddDT = DateTime.Now;
				jcontent.In = order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU;
				jcontent.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				jcontent.Operator = "Sys";
				jcontent.GetNO = content.NO;
				jcontent.Name = content.Name;
				jcontent.OrderMoney = order.PV;
				jcontent.OrderNo = order.OrderNo;
				jcontent.Out = 0;
				jcontent.Remarks = "得到管理费:" + (order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI).ToString("0.##") + "物流津贴:" + (order.PV * Models.WebConfig.FUWUZHONGXINWULIU).ToString("0.##");
				jcontent.State = 1;
				jcontent.Rest = order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU + content.Money;
				jcontent.Type = Models.Journal.TypeClass.GUANLI;
				jcontent.Title = Models.Journal.TypeClass.GetType(jcontent.Type) + ";订单:" + order.OrderNo;
				jcontent._id = ObjectId.GenerateNewId();

				var contentresult = tool.AddOneAsync(jcontent);

				Models.Journal admin = new Models.Journal();

				admin.AddDT = DateTime.Now;
				admin.In = 0;
				admin.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				admin.Operator = "Sys";
				admin.GetNO = "Sys";
				admin.Name = "Sys";
				admin.OrderMoney = order.PV;
				admin.OrderNo = order.OrderNo;
				admin.Out = order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU;
				admin.Remarks = "补贴 管理费:" + (order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI).ToString("0.##") + "物流津贴:" + (order.PV * Models.WebConfig.FUWUZHONGXINWULIU).ToString("0.##");
				admin.State = 1;
				admin.Rest = 0;
				admin.Type = Models.Journal.TypeClass.BUTIE;
				admin.Title = Models.Journal.TypeClass.GetType(admin.Type) + ";订单:" + order.OrderNo;
				admin._id = ObjectId.GenerateNewId();
				var adminresult = tool.AddOneAsync(admin);

				var cupdate = Builders<Models.User>.Update.Set("Money", order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU + content.Money);

				var caddresult = tool.UpdateOne(content._id.ToString(), cupdate);

				str += "服务中心:" + content.Name + " 编号:" + content.NO + "得到:" + (order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU).ToString("0.##") + ";";

				var cfilter = Builders<Models.User>.Filter.Eq("NO", content.Cantent);

				var company = tool.GetOne(cfilter);

				adminmoney = adminmoney - (order.PV * Models.WebConfig.FUWUZHONGXINGUANLIFEI + order.PV * Models.WebConfig.FUWUZHONGXINWULIU);

				if (adminu != null)
				{
					var cupdatead = Builders<Models.User>.Update.Set("Money", adminmoney);

					var adminupdate = tool.UpdateOne(adminu._id.ToString(), cupdatead);
				}


				if (company != null)
				{
					Models.Journal jcompany = new Models.Journal();

					jcompany.AddDT = DateTime.Now;
					jcompany.In = order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU;
					jcompany.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
					jcompany.Operator = "Sys";
					jcompany.GetNO = company.NO;
					jcompany.Name = company.Name;
					jcompany.OrderMoney = order.PV;
					jcompany.OrderNo = order.OrderNo;
					jcompany.Out = 0;
					jcompany.Remarks = "得到管理费:" + (order.PV * Models.WebConfig.GONGSHIGUANLIFEI).ToString("0.##") + "物流津贴:" + (order.PV * Models.WebConfig.GONGSHIWULIU).ToString("0.##");
					jcompany.State = 1;
					jcompany.Rest = order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU + company.Money;
					jcompany.Type = Models.Journal.TypeClass.GUANLI;
					jcompany.Title = Models.Journal.TypeClass.GetType(jcompany.Type) + ";订单:" + order.OrderNo;
					jcompany._id = ObjectId.GenerateNewId();

					var comresult = tool.AddOneAsync(jcompany);

					Models.Journal admin1 = new Models.Journal();

					admin1.AddDT = DateTime.Now;
					admin1.In = 0;
					admin1.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
					admin1.Operator = "Sys";
					admin1.GetNO = "Sys";
					admin1.Name = "Sys";
					admin1.OrderMoney = order.PV;
					admin1.OrderNo = order.OrderNo;
					admin1.Out = order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU;
					admin1.Remarks = "补贴 管理费:" + (order.PV * Models.WebConfig.GONGSHIGUANLIFEI).ToString("0.##") + "物流津贴:" + (order.PV * Models.WebConfig.GONGSHIWULIU).ToString("0.##");
					admin1.State = 1;
					admin1.Rest = 0;
					admin1.Type = Models.Journal.TypeClass.BUTIE;
					admin1.Title = Models.Journal.TypeClass.GetType(admin1.Type) + ";订单:" + order.OrderNo;
					admin1._id = ObjectId.GenerateNewId();
					var admin1result = tool.AddOneAsync(admin1);
					adminmoney = adminmoney - (order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU);

					if (adminu != null)
					{
						var cupdatead = Builders<Models.User>.Update.Set("Money", adminmoney);

						var adminupdate = tool.UpdateOne(adminu._id.ToString(), cupdatead);
					}

					var comupdate = Builders<Models.User>.Update.Set("Money", order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU + company.Money);

					var comaddresult = tool.UpdateOne(company._id.ToString(), comupdate);
					str += "公司:" + company.Name + " 编号:" + company.NO + "得到:" + (order.PV * Models.WebConfig.GONGSHIGUANLIFEI + order.PV * Models.WebConfig.GONGSHIWULIU).ToString("0.##") + ";";
				}

			}

			return str;
		}

		/// <summary>
		/// 月结财务报表
		/// </summary>
		/// <param name="No">用户编号</param>
		public static Task MonthJournalAsyc(string No)
		{
			return Task.Factory.StartNew(() =>
			{
				MonthJournal(No);

			});
		}

		/// <summary>
		/// 月结财务报表
		/// </summary>
		/// <param name="No">用户编号</param>
		public static void MonthJournal(string No)
		{
			Repository.Repository tool = new Repository.Repository();

			var date = DateTime.Now.AddMonths(-1);
			var datestr = date.Year.ToString("") + "," + date.Month;
			var filterM = Builders<Models.Monthl>.Filter.Where(p => p.DataDT == datestr);
			var month = tool.Count(filterM);
			if (month == 0)
			{
				var filter = Builders<Models.Journal>.Filter.Where(p => p.GetNO == No);
				var list = tool.GetMany(filter);
				int[] intarra = { 0, 1, 2, 3, 4 };
				for (int i = 0; i < intarra.Count(); i++)
				{
					var temp = list.FindAll(p => p.Type == intarra[i]);

					decimal money = 0;

					foreach (var item in temp)
					{
						money += item.In;
					}

					Models.Monthl monthly = new Models.Monthl();
					monthly._id = ObjectId.GenerateNewId();
					monthly.Type = intarra[i];
					monthly.Money = money;
					monthly.DataDT = date.Year + "," + date.Month;
					monthly.DataStr = date.Year + "年" + date.Month + "月";
					monthly.AddDT = DateTime.Now.ToShortDateString();
					var monthleyresult = tool.AddOneAsync(monthly);
				}

			}

		}

		///// <summary>
		///// 给上级反钱和经验异步方法
		///// </summary>
		///// <param name="order">订单编号</param>
		///// <param name="diyisale">售卖人</param>
		//public static Task BalanceAsyc(Models.Order order, Models.User diyisale)
		//{
		//	return Task.Factory.StartNew(() =>
		//	{
		//		Balance(order, diyisale);

		//	});
		//}


		/// <summary>
		/// 月结产品报表
		/// </summary>
		public static Task MonthProductAsyc()
		{
			return Task.Factory.StartNew(() =>
			{
				MonthProduct();

			});
		}

		/// <summary>
		/// 月结产品报表
		/// </summary>
		/// <param name="date">上个月1月1号</param>
		public static void MonthProduct()
		{
			Repository.Repository tool = new Repository.Repository();

			var date = new DateTime(DateTime.Now.AddMonths(-1).Year, DateTime.Now.AddMonths(-1).Month, 1);

			var list = tool.GetAll<Models.Products>();

			foreach (var item in list)
			{

				decimal mon = 0;

				int num = 0;

				var filterM = Builders<Models.Order>.Filter.Where(p => p.AddDT >= date && p.AddDT < date.AddMonths(1));
				var pro = tool.GetMany(filterM);

				foreach (var p in pro)
				{
					foreach (var pr in p.Products)
					{
						if (pr.No == item.ProNo)
						{
							mon += pr.Money * pr.Num;
							num += pr.Num;
						}
					}
				}
				Models.MonthPro product = new Models.MonthPro();

				product._id = ObjectId.GenerateNewId();
				product.ProNo = item.ProNo;
				product.ProName = item.Name;
				product.Num = num;
				product.TotlMoney = mon;
				product.Money = item.Money;
				product.AddDT = DateTime.Now;
				product.DataDT = date.Year + "," + date.Month;
				product.DataStr = date.Year + "年" + date.Month + "月";
				var monthleyresult = tool.AddOneAsync(product);

			}
		}



		/// <summary>
		/// 月结上个月的订单异步方法
		/// </summary>
		/// <param name="order">订单编号</param>
		/// <param name="diyisale">售卖人</param>
		public static Task MonthlyAsyc(DateTime date)
		{
			return Task.Factory.StartNew(() =>
			{
				Monthly(date);

			});
		}

		/// <summary>
		/// 月结上个月的订单
		/// </summary>
		/// <param name="date">上个月1月1号</param>
		public static void Monthly(DateTime date)
		{
			Repository.Repository tool = new Repository.Repository();

			var filterML = Builders<Models.Order>.Filter.Where(p => p.AddDT >= date);

			var list = tool.GetMany(filterML);

			decimal mon = 0;

			foreach (var item in list)
			{
				mon += item.Money;
			}

			Models.Monthl monthly = new Models.Monthl();

			monthly._id = ObjectId.GenerateNewId();
			monthly.Type = Models.Monthl.TypeClass.ORDER;
			monthly.Money = mon;
			monthly.DataDT = date.Year + "," + date.Month;
			monthly.DataStr = date.Year + "年" + date.Month + "月";
			monthly.AddDT = DateTime.Now.ToShortDateString();

			var monthleyresult = tool.AddOneAsync(monthly);

		}


		/// <summary>
		/// 给上级反钱和经验(不修改数据库，只计算)
		/// </summary>
		/// <param name="order">订单编号</param>
		/// <param name="diyisale">售卖人</param>
		public string NoBalance(Models.Order order, Models.User diyisale)
		{
			Repository.Repository tool = new Repository.Repository();
			#region 算向上分成

			var sale = diyisale;

			int dengji = -1;

			int congfu = 0;

			string str = "";

			decimal shengyu = order.Money;

			while (sale != null)//(!string.IsNullOrEmpty(sale.MUP))
			{

				if (sale.IsMStop)
				{
					dengji = 0;

					if (string.IsNullOrEmpty(sale.MUP))
					{
						break;
					}

					var filtc = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

					sale = tool.GetOne(filtc);

					if (sale == null)
					{
						break;
					}

					continue;
				}


				if (dengji == -1)
				{

					int type = Models.Journal.TypeClass.ZHITUI;

					var rate = Models.WebConfig.ZHITUIJIANG[sale.Level];

					var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

					shengyu = shengyu - money;

					str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

					#region 返给服务中心

					str += SetContent(order);

					#endregion

				}
				else
				{
					if (sale.Level == dengji && sale.Level >= Models.User.LevelClass.ZHIDAO)//第二次进来与上级等级一样时产生育成将
					{
						congfu += 1;
						Decimal rate = 0;
						switch (congfu)
						{
							case 1:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.06M;
								}
								else
								{
									rate = 0.01M;
								}
								break;

							case 2:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.03M;
								}
								else
								{
									rate = 0.01M;
								}
								break;
							case 3:
								if (sale.Level == Models.User.LevelClass.DAOSHI)
								{
									rate = 0.02M;
								}
								else if (sale.Level == Models.User.LevelClass.LAOSHI || sale.Level == Models.User.LevelClass.YUANSHI)
								{
									rate = 0.01M;
								}
								break;
							case 4:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.01M;
								}
								break;
							case 5:
								if (sale.Level >= Models.User.LevelClass.DAOSHI)
								{
									rate = 0.01M;
								}
								break;
							case 6:
								if (sale.Level == Models.User.LevelClass.DAOSHI)
								{
									rate = 0.01M;
								}
								else if (sale.Level == Models.User.LevelClass.YUANSHI)
								{
									rate = 0.005M;
								}
								break;
							default:
								rate = 0;
								break;
						}

						if (rate > 0)
						{
							var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

							shengyu = shengyu - money;


							str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

							//#region 返给服务中心

							//str += SetContent(order, sale.Cantent);

							//#endregion

						}

					}
					else if (sale.Level > dengji)
					{
						Decimal rate = Models.WebConfig.ZHITUIJIANG[sale.Level] - Models.WebConfig.ZHITUIJIANG[dengji];
						var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

						str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

						shengyu = shengyu - money;

						//#region 返给服务中心

						//str += SetContent(order, sale.Cantent);

						//#endregion

						congfu = 0;

					}
					else if (sale.Level < dengji)
					{
						var filts = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

						sale = tool.GetOne(filts);

						if (sale == null)
						{
							break;
						}

						continue;
					}

				}

				dengji = sale.Level;

				if (string.IsNullOrEmpty(sale.MUP))
				{
					break;
				}

				var filt = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

				sale = tool.GetOne(filt);

				if (sale == null)
				{
					break;
				}

			}

			shengyu = shengyu - order.PV * 0.1M;



			#endregion

			return str;

		}


		/// <summary>
		/// 给上级反钱和经验
		/// </summary>
		/// <param name="order">订单编号</param>
		/// <param name="diyisale">售卖人</param>
		public string Balance(Models.Order order, Models.User diyisale)
		{
			Repository.Repository tool = new Repository.Repository();
			#region 算向上分成

			var sale = diyisale;

			int dengji = -1;

			int congfu = 0;

			string str = "";

			decimal shengyu = order.Money;

			while (sale != null)//(!string.IsNullOrEmpty(sale.MUP))
			{

				if (sale.IsMStop)
				{
					dengji = 0;

					if (string.IsNullOrEmpty(sale.MUP))
					{
						break;
					}

					var filtc = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

					sale = tool.GetOne(filtc);

					if (sale == null)
					{
						break;
					}

					continue;
				}


				if (dengji == -1)
				{

					int type = Models.Journal.TypeClass.ZHITUI;

					var rate = Models.WebConfig.ZHITUIJIANG[sale.Level];

					var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

					Models.Journal journal = new Models.Journal();

					journal.AddDT = DateTime.Now;
					journal.In = money;
					journal.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
					journal.Operator = "Sys";
					journal.GetNO = sale.NO;
					journal.Name = sale.Name;
					journal.OrderMoney = order.PV;
					journal.OrderNo = order.OrderNo;
					journal.Out = 0;
					journal.Remarks = "奖金:" + (order.PV * rate).ToString("0.##") + "; 管理费:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate).ToString("0.##") + "; 爱心基金:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate).ToString("0.##");
					journal.State = 1;
					journal.Rest = money + sale.Money;
					journal.Type = type;
					journal.Title = Models.Journal.TypeClass.GetType(journal.Type) + ";订单:" + order.OrderNo;
					journal._id = ObjectId.GenerateNewId();




					var journalresult = tool.AddOneAsync(journal);

					var update = Builders<Models.User>.Update.Set("Money", money + sale.Money);

					shengyu = shengyu - money;

					var addresult = tool.UpdateOne(sale._id.ToString(), update);

					str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

					#region 返给服务中心

					str += SetContent(order);

					#endregion

				}
				else
				{
					if (sale.Level == dengji && sale.Level >= Models.User.LevelClass.ZHIDAO)//第二次进来与上级等级一样时产生育成将
					{
						congfu += 1;
						Decimal rate = 0;
						switch (congfu)
						{
							case 1:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.06M;
								}
								else
								{
									rate = 0.01M;
								}
								break;

							case 2:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.03M;
								}
								else
								{
									rate = 0.01M;
								}
								break;
							case 3:
								if (sale.Level == Models.User.LevelClass.DAOSHI)
								{
									rate = 0.02M;
								}
								else if (sale.Level == Models.User.LevelClass.LAOSHI || sale.Level == Models.User.LevelClass.YUANSHI)
								{
									rate = 0.01M;
								}
								break;
							case 4:
								if (sale.Level >= Models.User.LevelClass.LAOSHI)
								{
									rate = 0.01M;
								}
								break;
							case 5:
								if (sale.Level >= Models.User.LevelClass.DAOSHI)
								{
									rate = 0.01M;
								}
								break;
							case 6:
								if (sale.Level == Models.User.LevelClass.DAOSHI)
								{
									rate = 0.01M;
								}
								else if (sale.Level == Models.User.LevelClass.YUANSHI)
								{
									rate = 0.005M;
								}
								break;
							default:
								rate = 0;
								break;
						}

						if (rate > 0)
						{
							var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

							Models.Journal journal = new Models.Journal();

							journal.AddDT = DateTime.Now;
							journal.In = money;
							journal.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
							journal.Operator = "Sys";
							journal.GetNO = sale.NO;
							journal.Name = journal.Name;
							journal.OrderMoney = order.PV;
							journal.OrderNo = order.OrderNo;
							journal.Out = 0;
							journal.Remarks = "奖金:" + (order.PV * rate).ToString("0.##") + "; 管理费:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate).ToString("0.##") + "; 爱心基金:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate).ToString("0.##");
							journal.State = 1;
							journal.Rest = money + sale.Money;
							journal.Type = Models.Journal.TypeClass.YUCHENG;
							journal.Title = Models.Journal.TypeClass.GetType(journal.Type) + ";订单:" + order.OrderNo;
							journal._id = ObjectId.GenerateNewId();

							var journalresult = tool.AddOneAsync(journal);

							var update = Builders<Models.User>.Update.Set("Money", money + sale.Money);

							shengyu = shengyu - money;

							var addresult = tool.UpdateOne(sale._id.ToString(), update);

							str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

							//#region 返给服务中心

							//str += SetContent(order, sale.Cantent);

							//#endregion

						}

					}
					else if (sale.Level > dengji)
					{
						Decimal rate = Models.WebConfig.ZHITUIJIANG[sale.Level] - Models.WebConfig.ZHITUIJIANG[dengji];
						var money = order.PV * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate - order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate;

						Models.Journal journal = new Models.Journal();

						journal.AddDT = DateTime.Now;
						journal.In = money;
						journal.GetNO = sale.NO;
						journal.Name = sale.Name;
						journal.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
						journal.Operator = "Sys";
						journal.OrderMoney = order.PV;
						journal.OrderNo = order.OrderNo;
						journal.Out = 0;
						journal.Remarks = "奖金:" + (order.PV * rate).ToString("0.##") + "; 管理费:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIGUANLIFEI * rate).ToString("0.##") + "; 爱心基金:" + (order.PV * Models.WebConfig.ZHIYOUGONGSHIWULIU * rate).ToString("0.##");
						journal.State = 1;
						journal.Rest = money + sale.Money;
						journal.Type = Models.Journal.TypeClass.CHAE;
						journal.Title = Models.Journal.TypeClass.GetType(journal.Type) + ";订单:" + order.OrderNo;
						journal._id = ObjectId.GenerateNewId();

						var journalresult = tool.AddOneAsync(journal);

						var update = Builders<Models.User>.Update.Set("Money", money + sale.Money);

						var addresult = tool.UpdateOne(sale._id.ToString(), update);

						str += "用户:" + sale.Name + "编号:" + sale.NO + "得到奖金:" + (money).ToString("0.##") + ";";

						shengyu = shengyu - money;

						//#region 返给服务中心

						//str += SetContent(order, sale.Cantent);

						//#endregion

						congfu = 0;

					}
					else if (sale.Level < dengji)
					{
						var filts = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

						sale = tool.GetOne(filts);

						if (sale == null)
						{
							break;
						}

						continue;
					}

				}

				dengji = sale.Level;

				if (string.IsNullOrEmpty(sale.MUP))
				{
					break;
				}

				var filt = Builders<Models.User>.Filter.Eq("NO", sale.MUP);

				sale = tool.GetOne(filt);

				if (sale == null)
				{
					break;
				}

			}

			shengyu = shengyu - order.PV * 0.1M;

			var firterandmin = Builders<Models.User>.Filter.Where(p => p.UserType == Models.User.TypeClass.ADMIN);

			var adminu = tool.GetOne(firterandmin);

			Models.Journal journals = new Models.Journal();

			journals.AddDT = DateTime.Now;
			journals.In = shengyu;
			journals.GetNO = "Sys";
			journals.Name = "Sys";
			journals.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
			journals.Operator = "Sys";
			journals.OrderMoney = order.Money;
			journals.OrderNo = order.OrderNo;
			journals.Out = 0;
			journals.Remarks = "进账:" + shengyu;
			journals.State = 1;
			journals.Rest = shengyu + adminu.Money;
			journals.Type = Models.Journal.TypeClass.JINZHANG;
			journals.Title = Models.Journal.TypeClass.GetType(journals.Type) + ";订单:" + order.OrderNo;
			journals._id = ObjectId.GenerateNewId();

			var journalresults = tool.AddOneAsync(journals);


			var update1 = Builders<Models.User>.Update.Set("Money", shengyu + adminu.Money);

			var updateadmin = tool.UpdateOne(adminu._id.ToString(), update1);

			#endregion


			#region 经验分成

			var sales = diyisale;


			while (sales != null)//!string.IsNullOrEmpty(sales.EUP)
			{

				if (sales.IsEStop)
				{
					if (string.IsNullOrEmpty(sales.EUP))
					{
						break;
					}

					var filtc = Builders<Models.User>.Filter.Eq("NO", sales.EUP);

					sales = tool.GetOne(filtc);

					if (sales == null)
					{
						break;
					}
					continue;
				}


				if (sales.UserType == Models.User.TypeClass.User)
				{
					if (sales.Level < Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + order.PV) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString()).Set("Level", sales.Level + 1);

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
					}
					else if (sales.Level == Models.User.LevelClass.LAOSHI && (Convert.ToInt32(sales.EXP) + order.PV) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level == Models.User.LevelClass.LAOSHI);
						var count = tool.Count(fil);
						if (count >= 2)
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString()).Set("Level", sales.Level + 1);

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
						}
						else
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString());

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
						}
					}
					else if (sales.Level == Models.User.LevelClass.DAOSHI && (Convert.ToInt32(sales.EXP) + order.PV) > Convert.ToInt32(Models.WebConfig.DENGJIDIANSHU[sales.Level + 1]))
					{
						var fil = Builders<Models.User>.Filter.Where(p => p.EUP == sales.NO && p.Level == Models.User.LevelClass.DAOSHI);
						var count = tool.Count(fil);
						if (count >= 4 || ((Convert.ToInt32(sales.EXP) + order.PV) > 18000000 && count >= 3) || ((Convert.ToInt32(sales.EXP) + order.PV) > 24000000 && count >= 2))
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString()).Set("Level", sales.Level + 1);

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
						}
						else
						{
							var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString());

							var addresult = tool.UpdateOne(sales._id.ToString(), update);
						}
					}
					else
					{
						var update = Builders<Models.User>.Update.Set("EXP", (Convert.ToInt32(sales.EXP) + order.PV).ToString());

						var addresult = tool.UpdateOne(sales._id.ToString(), update);
					}

				}

				if (string.IsNullOrEmpty(sales.EUP))
				{
					break;
				}

				var filt = Builders<Models.User>.Filter.Eq("NO", sales.EUP);

				sales = tool.GetOne(filt);

				if (sales == null)
				{
					break;
				}

			}

			#endregion

			return str;

		}


		/// <summary>
		/// 订单详情
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public ActionResult OrderPro(string id)
		{
			Repository.Repository tool = new Repository.Repository();
			var filter = Builders<Models.Order>.Filter.Where(p => p.OrderNo == id);
			var order = tool.GetOne<Models.Order>(filter);
			return View(order);
		}



		/// <summary>
		/// 确认提现
		/// </summary>
		/// <param name="id">记录标识</param>
		/// <param name="userId">提现者用户标识</param>
		/// <param name="content">拒绝理由,如为空折不拒绝</param>
		/// <returns></returns>
		public JsonResult ConfirmWithdraw(string id, string content)
		{
			Repository.Repository tool = new Repository.Repository();

			var journal = tool.GetOne<Models.Journal>(id);

			if (journal == null)
			{
				return Json(new { Code = "FAIL", Msg = "记录不存在" });
			}

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == journal.GetNO);
			var entity = tool.GetOne(filter);
			if (entity == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户不存在" });
			}


			if (entity.Freeze < journal.Out)
			{
				return Json(new { Code = "FAIL", Msg = "余额不足" });
			}

			if (string.IsNullOrEmpty(content))
			{
				var updatau = Builders<Models.User>.Update.Set("Freeze", entity.Freeze - journal.Out);

				var updataj = Builders<Models.Journal>.Update.Set("State", 1);

				var resultu = tool.UpdateOne(entity._id.ToString(), updatau);

				var resultj = tool.UpdateOne(id, updataj);

				Models.Journal journals = new Models.Journal();
				journals.AddDT = DateTime.Now;
				journals.In = 0;
				journals.GetNO = entity.NO;
				journals.Name = entity.Name;
				journals.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				journals.Operator = "Sys";
				journals.Out = journal.Out;
				journals.OrderMoney = 0;
				journals.OrderNo = "";
				journals.Remarks = "提现成功";
				journals.State = 1;
				journals.Rest = entity.Money + journal.Out;
				journals.Type = Models.Journal.TypeClass.WITHDRAW;
				journals.Title = Models.Journal.TypeClass.GetType(journals.Type) + ";";
				journals._id = ObjectId.GenerateNewId();

				var resultjo = tool.AddOneAsync(journals);

				return Json(new { Code = "OK", Msg = "确认成功" });
			}
			else
			{
				//提现失败

				Models.Journal journals = new Models.Journal();
				journals.AddDT = DateTime.Now;
				journals.In = journal.Out;
				journals.GetNO = entity.NO;
				journals.Name = entity.Name;
				journals.JournalNO = DateTime.Now.ToString("yyyyMMddHHmmssffff");
				journals.Operator = "Sys";
				journals.Out = 0;
				journals.OrderMoney = 0;
				journals.OrderNo = "";
				journals.Remarks = "由于:" + content + "原因,提现失败!" + journal.Out + "已退回到您的账户;";
				journals.State = 1;
				journals.Rest = entity.Money + journal.Out;
				journals.Type = Models.Journal.TypeClass.WITHDRAW;
				journals.Title = Models.Journal.TypeClass.GetType(journals.Type) + ";";
				journals._id = ObjectId.GenerateNewId();

				var result = tool.AddOneAsync(journals);


				//给用户返回金额
				var updatau = Builders<Models.User>.Update.Set("Freeze", entity.Freeze - journal.Out).Set("Money",entity.Money+ journal.Out);

				var updataj = Builders<Models.Journal>.Update.Set("State", 1);

				var resultu = tool.UpdateOne(entity._id.ToString(), updatau);

				var resultj = tool.UpdateOne(id, updataj);

				return Json(new { Code = "OK", Msg = "已拒绝" });
			}
		}


		/// <summary>
		/// 如果同意该订单，即将得到钱数的用户
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult GetData(string id)
		{
			
			if (string.IsNullOrEmpty(id))
			{
				return Json(new { Code = "FAIL", Msg = "标识丢失" });
			}

			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null || user.UserType != Models.User.TypeClass.ADMIN)
			{
				return Json(new { Code="FAIL",Msg= "用户权限不够或未登陆" });
			}

			var order = tool.GetOne<Models.Order>(id);

			if (order == null)
			{
				return Json(new { Code = "FAIL", Msg = "订单不存在" });
			}

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == order.SaleNo);

			var saleUser = tool.GetOne(filter);

			
			if (saleUser != null)
			{
				return Json(new { Code = "OK", Msg = "查询成功", Str = "测试数据" });

				var str = NoBalance(order, saleUser);
				//return Json(new { Code = "OK", Msg = "查询成功",Str= str });
			}
			return Json(new { Code = "FAIL", Msg = "数据错误"});
		}




		/// <summary>
		/// 修改订单状态
		/// </summary>
		/// <param name="id">订单标识</param>
		/// <param name="state">订单状态</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult EditOrderState(string id, int state)
		{
			if (string.IsNullOrEmpty(id))
			{
				return Json(new { Code = "FAIL", Msg = "标识为空" });
			}

			Repository.Repository tool = new Repository.Repository();

			var user = tool.GetOne<Models.User>(Services.Cookie.GetId());

			if (user == null || user.UserType != Models.User.TypeClass.ADMIN)
			{
				return Json(new { Code = "FAIL", Msg = "用户权限不够或未登陆" });
			}

			var order = tool.GetOne<Models.Order>(id);

			if (order == null)
			{
				return Json(new { Code = "FAIL", Msg = "订单不存在" });
			}

			var updatau = Builders<Models.Order>.Update.Set("State", state);

			var result = tool.UpdateOne(order._id.ToString(), updatau);

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == order.SaleNo);

			var saleUser = tool.GetOne(filter);

			if (saleUser != null && state == Models.Order.StateClass.PASS)
			{
				string str = "已修改";

				str = Balance(order, saleUser);

				var date = new DateTime(DateTime.Now.AddMonths(-1).Year, DateTime.Now.AddMonths(-1).Month, 1);

				var datestr = date.Year + "," + date.Month;

				var filterM = Builders<Models.Monthl>.Filter.Where(p => p.DataDT == datestr && p.Type == 5);
				var month = tool.Count(filterM);
				if (month == 0)
				{
					//MonthlyAsyc(date);
				}

				var filterPs = Builders<Models.MonthPro>.Filter.Where(p => p.DataDT == datestr);

				var monthPro = tool.Count(filterPs);

				if (monthPro == 0)
				{

					//MonthProductAsyc();
				}

				//MonthJournalAsyc(user.NO);
				return Json(new { Code = "OK", Msg = "已修改", Str = str });
			}

			return Json(new { Code = "OK", Msg = "已修改", Str = "已修改" });
		}

		/// <summary>
		/// 根据订单添加用户
		/// </summary>
		/// <param name="id">订单标识</param>
		/// <param name="exp">经验上级</param>
		/// <param name="bankNo">银行卡号</param>
		/// <param name="bankName">银行名称</param>
		/// <param name="card">身份证好</param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult AddUser(string id, string exp, string bankNo, string bankName, string card, string Mobile, string userName)
		{
			Repository.Repository tool = new Repository.Repository();

			var users = tool.GetOne<Models.User>(Services.Cookie.GetId());
			if (users == null)
			{
				return Json(new { Code = "FAIL", Msg = "用户存在" });
			}

			var order = tool.GetOne<Models.Order>(id);

			if (order == null)
			{
				return Json(new { Code = "FAIL", Msg = "订单不存在" });
			}

			var filter = Builders<Models.User>.Filter.Where(p => p.Card == card);
			var count = tool.Count(filter);

			if (count > 0)
			{
				return Json(new { Code = "FAIL", Msg = "用户信息已存在" });
			}

			if (!string.IsNullOrEmpty(order.UserNo))
			{
				return Json(new { Code = "FAIL", Msg = "学员编号已存在" });
			}


			#region 注册用户

			string con = "";
			List<string> arr = null;

			if (!string.IsNullOrEmpty(exp))
			{
				var filterexp = Builders<Models.User>.Filter.Eq("NO", exp);

				var entity = tool.GetOne(filterexp);

				if (entity == null)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不存在" });
				}
				if (entity.UserType != Models.User.TypeClass.User)
				{
					return Json(new { Code = "FAIL", Msg = "上级用户不能是服务商或公司" });
				}

				bool isOk = false;

				string ep = order.SaleNo;

				if (exp != order.SaleNo)
				{
					var filterexps = Builders<Models.User>.Filter.Eq("EUP", entity.NO);

					var entitys = tool.Count(filterexps);//该用户是否有已经有一条线

					if (entitys > 0)
					{
						return Json(new { Code = "FAIL", Msg = "请填写末级用户编号" });
					}

					string temp = exp;
					while (!string.IsNullOrEmpty(temp))
					{
						var filtertem = Builders<Models.User>.Filter.Eq("NO", temp);
						var tempentity = tool.GetOne(filtertem);
						if (tempentity != null && !string.IsNullOrEmpty(tempentity.EUP))
						{
							if (tempentity.EUP == order.SaleNo)
							{
								isOk = true;
								break;
							}
							temp = tempentity.EUP;
						}
						else
						{
							break;
						}
					}
					if (!isOk)
					{
						return Json(new { Code = "FAIL", Msg = "推荐人排列错误,请联系管理员核实" });
					}

					con = entity.Cantent;
				}
				else
				{
					if (entity.Bind != null && entity.Bind.Contains(users.NO))
					{
						con = users.NO;
					}
					else
					{
						con = entity.Cantent;
					}
				}

			}

			Models.User user = new Models.User();
			user.AddDT = DateTime.Now;
			user.EUP = exp;
			user.EXP = "1";
			user.Name = order.UserName;
			user.Mobile = order.Mobile;
			user.UserType = Models.User.TypeClass.User;
			user.Cantent = con;
			user.Level = Models.User.LevelClass.STUDENT;
			user.Money = 0;
			user.BankName = bankName;
			user.BankNO = bankNo;
			user.Card = card;
			user.UserName = userName;
			user.MUP = order.SaleNo;
			user.Bind = arr;
			user.Mobile = Mobile;
			var no = "";
			Models.User isUser = null;
			do
			{
				Random rans = new Random();
				int RandKeys = rans.Next(100000, 999999);

				no = "SY" + RandKeys;
				var filtersy = Builders<Models.User>.Filter.Eq("NO", no);
				isUser = tool.GetOne(filtersy);
			} while (isUser != null);

			user.NO = no;

			string pwd1 = GetRandomString(6);

			user.Pwd1 = Repository.FuBeiMD5.Sign(pwd1, Models.WebConfig.KEY, Models.WebConfig.UFT8);
			user.Pwd2 = user.Pwd1;
			user._id = ObjectId.GenerateNewId();
			var result = tool.AddOneAsync(user);

			#endregion

			var cupdate = Builders<Models.Order>.Update.Set("UserNo", user.NO).Set("Type", "学员注册");

			var resultc = tool.UpdateOne(order._id.ToString(), cupdate);

			return Json(new { Code = "OK", Msg = "注册成功", Account = user.NO, PWD1 = pwd1 });
		}

		/// <summary>
		/// 获取推荐人用户名
		/// </summary>
		/// <param name="no"></param>
		/// <returns></returns>
		[HttpPost]
		public JsonResult GetSeller(string no)
		{
			Repository.Repository tool = new Repository.Repository();

			var filter = Builders<Models.User>.Filter.Where(p => p.NO == no);
			var saleUser = tool.GetOne(filter);

			if (saleUser == null)
			{
				return Json(new { Code = "FAIL", Msg = "售货人不存在" });
			}

			return Json(new { Code = "OK", Msg = "注册成功", Name = saleUser.Name, UserName = saleUser.UserName });
		}


		///<summary>
		///生成随机字符串 
		///</summary>
		///<param name="length">目标字符串的长度</param>
		///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
		///<returns>指定长度的随机字符串</returns>
		public static string GetRandomString(int length)
		{
			byte[] b = new byte[4];
			new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
			Random r = new Random(BitConverter.ToInt32(b, 0));
			string s = null, str = "";
			str += "0123456789";
			//str += "abcdefghijklmnopqrstuvwxyz";
			//str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			//str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
			for (int i = 0; i < length; i++)
			{
				s += str.Substring(r.Next(0, str.Length - 1), 1);
			}
			return s;
		}

	}
}